<?php
class PackageController {
	public function __construct() {
		header('Content-type: application/json; charset=utf-8');
	}
	public function getAction() {
		if (!checkSign()) {
			echo makeJson(['error' => 'invalid_sign']);
			return;
		}
		$id = $_GET['id'];
		$version = $_GET['version'];
		$stable = $_GET['stable'];
		if (empty($id)) {
			echo makeJson(['error' => 'invalid_param']);
			return;
		}
		if (empty($version)) {
			$version = NULL;
			if (empty($stable)) {
				$stable = 1;
			}
		} else {
			$stable = NULL;
		}
		$rs = PackageModel::get($id, $version, $stable);
		if (empty($rs)) {
			echo makeJson(['error' => 'not_found']);
		} else {
			$rs['download'] = 'http://xmp.sy/data/package/' . $rs['download'];
			echo makeJson($rs);
		}
	}
	public function findAction() {
		if (!checkSign()) {
			echo makeJson(['error' => 'invalid_sign']);
			return;
		}
		$name = $_GET['name'];
		$fuzzyMatch = intval($fuzzyMatch);
		if (empty($name)) {
			echo makeJson(['error' => 'invalid_param']);
			return;
		}
		if ($fuzzyMatch) {
			$sql = 'SELECT id, name, version FROM xmp_package_meta WHERE name = ? LIMIT 0, 1';
			$data = [$name];
		} else {
			$sql = 'SELECT id, name, version FROM xmp_package_meta WHERE name LIKE ? LIMIT 0, 30';
			$data = ['%' . $name . '%'];
		}
		$rs = Database::getInstance()->query($sql, $data);
		if (empty($rs)) {
			echo makeJson(['list' => []]);
		} else {
			echo makeJson(['list' => $rs]);
		}
	}
	public function historyAction() {
		if (!checkSign()) {
			echo makeJson(['error' => 'invalid_sign']);
			return;
		}
		$id = $_GET['id'];
		if (empty($id)) {
			echo makeJson(['error' => 'invalid_param']);
			return;
		}
		$sql = 'SELECT version, description, stable, time FROM xmp_package WHERE pid = ? LIMIT 0, 50';
		$data = [$id];
		$rs = Database::getInstance()->query($sql, $data);
		if (empty($rs)) {
			echo makeJson(['list' => []]);
		} else {
			echo makeJson(['list' => $rs]);
		}
	}
}